#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int data_[100001]= {0},next_[100001]= {0};
vector<int> v1,v2,res;
int main() {
	int l1,l2,n,Address,Data,Next,i=0,j=0,cnt=0;
	cin>>l1>>l2>>n;
	for(int k=0; k<n; k++) {
		cin>>Address>>Data>>Next;
		data_[Address]=Data;
		next_[Address]=Next;
	}
	int *p1=&l1,*p2=&l2,k1,k2;
	while(*p1!=-1) {
		v1.push_back(*p1);
		p1=&next_[*p1];
	}
	while(*p2!=-1) {
		v2.push_back(*p2);
		p2=&next_[*p2];
	}
	if(v1.size()>=2*v2.size()) {
		reverse(v2.begin(),v2.end());
		while(i<v1.size()||j<v2.size()) {
			res.push_back(v1[i]);
			if((i+1)%2==0&&j<v2.size()) {
				res.push_back(v2[j]);
				j++;
			}
			i++;
		}
	} else {
		reverse(v1.begin(),v1.end());
		while(i<v1.size()||j<v2.size()) {
			res.push_back(v2[j]);
			if((j+1)%2==0&&i<v1.size()) {
				res.push_back(v1[i]);
				i++;
			}
			j++;
		}
	}
	for(int k=0; k<res.size(); k++) {
		if(k>0) printf("%05d\n",res[k]);
		printf("%05d %d ",res[k],data_[res[k]]);
	}
	cout<<"-1";
	return 0;
}
